package com.lge.remoteshot.network;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

import android.util.Log;

import com.lge.remoteshot.camera.CameraActivity;

public class ClientPreviewThread extends Thread {
	private CameraActivity activity;

	private DatagramSocket dSock;

	private byte[] buffer = new byte[128];
	private InetAddress host;
	private boolean runThread = true;

	public ClientPreviewThread(CameraActivity activity, String host) {
		// TODO Auto-generated constructor stub
		this.activity = activity;
		try {
			this.host = InetAddress.getByName(host);
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			dSock = new DatagramSocket();
			dSock.bind(null);
			dSock.connect(host, ServerManager.SERVER_PREVIEW_PORT);
			while (runThread) {
				DatagramPacket recvPacket = new DatagramPacket(buffer, 0, buffer.length);
				dSock.receive(recvPacket);
				byte[] receive = recvPacket.getData();
				String msg = new String(receive, 0, receive.length);
				activity.setReceivedAction(msg);
				Log.d(CameraActivity.TAG, "ClientThread:run:receivePacket:" + msg);
			}
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			Log.d(CameraActivity.TAG,
					"ClientThread:run:SocketException:" + e.toString() + e.getMessage());
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			Log.d(CameraActivity.TAG,
					"ClientThread:run:UnknownException:" + e.toString() + e.getMessage());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Log.d(CameraActivity.TAG,
					"ClientThread:run:IOException:" + e.toString() + e.getMessage());
		}

	}

	public void sendFrameData(byte[] data) {
		try {
			if (host != null && dSock != null) {
				DatagramPacket sendPacket = new DatagramPacket(data, 0, data.length, host,
						ServerManager.SERVER_PREVIEW_PORT);
				dSock.send(sendPacket);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Log.d(CameraActivity.TAG,
					"ClientThread:sendFrameData:IOException" + e.toString() + e.getMessage());
		}
	}

	public void stopThread() {
		runThread = false;
		if (dSock != null)
			dSock.close();
	}
}